package de.hfu.android;

import java.util.List;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.AsyncTask;
import de.hfu.helper.DataAccess;
import de.hfu.model.DayPlan;

public class RetrieveDataTask extends AsyncTask<Void, Void, List<DayPlan>> implements OnCancelListener {
	WeekViewListAdapter adapter;
	Context context;
	ProgressDialog dialog;
	boolean flagLoadAll;
	public static final int GET_ONE_WEEK = 0;
	public static final int GET_ALL = 1;

	public RetrieveDataTask(Context context, WeekViewListAdapter adapter, boolean flagLoadAll) {
		super();
		this.adapter = adapter;
		this.context = context;
		this.flagLoadAll = flagLoadAll;
	}
	
	@Override
	protected void onPreExecute() {
		String content = context.getResources().getString(R.string.loading);
		dialog = ProgressDialog.show(context, "", content, true, true);
		dialog.setOnCancelListener(this);
	}

	@Override
	protected List<DayPlan> doInBackground(Void... params) {
		DataAccess dac = DataAccess.getInstance(context);
		List<DayPlan> result = null;
		if (flagLoadAll)
			result = dac.loadAllDayPlansFromExternalStorage();
		else
			result = dac.loadDayPlansOfAWeekFromExternalStorage();
		
		return result;
//		try {			
//			//List<DayPlan> menuPlan = DataAccess.loadDayPlansFromExternalStorage(context);
//			//List<DayPlan> menuPlan = DataAccess.loadDayPlansOfThisWeekFromExternalStorage(context);			
//			List<DayPlan> menuPlan = dac.loadDayPlansOfAWeekFromExternalStorage();
//			if (menuPlan == null)
//				throw new IOException();
//			return menuPlan;
//		} catch (IOException e) {
//			e.printStackTrace();
//			// No data available
//			try {
//				List<DayPlan> menuPlan = DataParser
//						.getAllMenuFromRSSOnline(DataParser.FURTWANGEN_URL);
//				for (DayPlan dayPlan : menuPlan) {
//					dac.storeDayPlan2ExternalStorage(dayPlan);
//				}
//				return menuPlan;
//			} catch (MalformedURLException e1) {
//				// TODO Auto-generated catch block
//			} catch (ParseException e1) {
//				// TODO Auto-generated catch block
//				e1.printStackTrace();
//			} catch (IOException e1) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//		} catch (ClassNotFoundException e) {
//			e.printStackTrace();
//		}		
	}

	@Override
	protected void onPostExecute(List<DayPlan> result) {
		if (result != null) {
			adapter.setData(result);
			adapter.notifyDataSetChanged();
		}
		dialog.dismiss();
	}

	@Override
	public void onCancel(DialogInterface arg0) {
		this.cancel(true);
	}

}
